﻿using KinonekoSoftware.Extensions.Collections;

namespace KinonekoSoftware.CodariaDB.Documents.Theories
{
    public abstract class TheoryEngine<T> : _Full<T> where T : TheoryObject
    {
        public const string Text_Theory_Elements   = "Text.Theory.Elements";
        public const string Text_Theory_Rarity     = "Text.Theory.Rarity";
        public const string Text_Theory_Species    = "Text.Theory.BiologyClass";
        public const string Text_Theory_Mineral    = "Text.Theory.Mineral";
        public const string Text_Theory_Vocabulary = "Text.Theory.Vocabulary";
        public const string Text_Theory_Chikara    = "Text.Theory.Chikara";

        public const string ID_Element_CalledName     = "Element_Name";
        public const string ID_Element_ImagePlacement = "Element_Placement";


        protected TheoryEngine()
        {
            InternalCollection = new List<T>(16);
            Collection         = new ReadOnlyCollection<T>(InternalCollection);
        }

        protected internal sealed override void OnDatabaseOpeningInternal(RepositoryOpenContext context)
        {
            var repository = context.Repository;

            //
            //
            Repository = repository;

            //
            //
            base.OnDatabaseOpeningInternal(context);


            //
            //
            if (InternalCollection.Count > 0)
            {
                InternalCollection.Clear();
            }

            //
            //
            InternalCollection.AddMany(InsideDB.FindAll());
            
            Sort(InternalCollection);
        }

        protected virtual void Sort(IList<T> collection)
        {
            
        }
        
        public int Count() => InsideDB.Count();

        public string GetDefaultObject() => InternalCollection.FirstOrDefault()?.Id;

        public T GetTheory(string id)
        {
            var theory = InternalCollection.FirstOrDefault(x => x.Id == id);
            theory ??= InternalCollection.FirstOrDefault();
            return theory;
        }

        /// <summary>
        /// 属性的叫法
        /// </summary>
        public string CalledName
        {
            get => Repository.Strings[ID_Element_CalledName];
            set
            {
                Repository.Strings[ID_Element_CalledName] = value;
            }
        }

        /// <summary>
        /// 指定图标的放置方向，true为左，false为右
        /// </summary>
        public bool ImagePlacement
        {
            get => Repository.Booleans[ID_Element_ImagePlacement];
            set
            {
                Repository.Booleans[ID_Element_ImagePlacement] = value;
            }
        }

        protected List<T>          InternalCollection { get; }
        public    IRepository      Repository         { get; private set; }
        public    IReadOnlyList<T> Collection         { get; }
    }
}